using System;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace PS.WebParts.Rollup.GridViewWebPart
{
    public class UserColumn : FormattedColumn
    {
        private SPSite site;
        private bool usePresenceInfo = true;
        private bool useLoginName = false;

        static private int imnNumber = 0;

        public bool UsePresenceInfo
        {
            get { return usePresenceInfo; }
            set { usePresenceInfo = value; }
        }

        public bool UseLoginName
        {
            get { return useLoginName; }
            set { useLoginName = value; }
        }

        [XmlIgnore]
        public SPSite Site
        {
            set { site = value; }
            get
            {
                if (null == site)
                {
                    return SPContext.Current.Site;
                }
                return site;
            }
        }

        private static SPUser ResolveUser(SPWeb web, string value)
        {
            SPUser result = null;

            try
            {
                SPFieldUserValue userValue = new SPFieldUserValue(web, value.ToString());
                result = userValue.User;
            }
            catch (ArgumentException)
            {
                foreach (SPUser user in web.SiteUsers)
                {
                    if (user.Name == value)
                    {
                        result = user;
                        break;
                    }
                }
            }

            return result;
        }

        internal override string GetDisplayString(object container)
        {
            string result;

            object value = DataBinder.GetPropertyValue(container, DataField);
            using (SPWeb web = Site.OpenWeb(new Guid(DataBinder.GetPropertyValue(container, "_WebId").ToString())))
            {
                SPUser user = ResolveUser(web, value.ToString());

                if (useLoginName)
                {
                   result = SPHttpUtility.HtmlEncode(user.LoginName);
                }
                else
                {
                    result = SPHttpUtility.HtmlEncode(user.Name);
                }

            }
            return result;
        }

        internal override string GetFormatedString(object container)
        {
            object value = DataBinder.GetPropertyValue(container, DataField);
            if (null == value || value.ToString() == string.Empty)
            {
                return string.Empty;
            }
            
            StringBuilder sb = new StringBuilder();

            using (SPWeb web = Site.OpenWeb(new Guid(DataBinder.GetPropertyValue(container, "_WebId").ToString())))
            {
                SPUser user = ResolveUser(web, value.ToString());

                string serverRelativeUrl = Site.ServerRelativeUrl;
                if (!serverRelativeUrl.EndsWith("/"))
                {
                    serverRelativeUrl = serverRelativeUrl + "/";
                } 
                
                string str = SPHttpUtility.HtmlUrlAttributeEncode(SPHttpUtility.UrlPathEncode(serverRelativeUrl + "_layouts/userdisp.aspx", false));
                
                sb.Append("<nobr><span>");
                sb.Append("<A HREF=\"");
                sb.Append(str);
                sb.Append("?ID=");
                sb.Append(user.ID.ToString(CultureInfo.InvariantCulture));
                sb.Append("\">");
                
                if (useLoginName)
                {
                    sb.Append(SPHttpUtility.HtmlEncode(user.LoginName));
                }
                else
                {
                    sb.Append(SPHttpUtility.HtmlEncode(user.Name));
                }

                sb.Append("</A>");
                
                if (usePresenceInfo)
                {
                    int num = Interlocked.Increment(ref imnNumber);
                    sb.Append("<img border=\"0\" height=\"1\" width=\"3\" src=\"/_layouts/images/blank.gif\"/><img border=\"0\" height=\"12\" width=\"12\" src=\"/_layouts/images/blank.gif\" onload=\"IMNRC('" + user.Email + "')\" id=\"imn" + num.ToString() + "\" >");
                }

                #region commented 'alternative realization'
//                sb.Append("<img border=\"0\" height=\"1\" width=\"3\" src=\"/_layouts/images/blank.gif\"/>");
//                sb.Append(GetImnPawnHtml(user.SipAddress, user.User.Email) );
                #endregion
                sb.Append("</span></nobr>");
            }

            return sb.ToString();
        }

        #region commented 'alternative realization'
//        private static string GetImnPawnHtml(string sip, string email)
//        {
//            int num = Interlocked.Increment(ref imnNumber);
//            string valueToEncode = SPUtility.GetLocalizedString("$Resources:core,userinfo_schema_nopresenceinfo;", "core", (uint)Thread.CurrentThread.CurrentUICulture.LCID);
//            if (string.IsNullOrEmpty(sip))
//            {
//                while (!string.IsNullOrEmpty(email))
//                {
//                    return string.Format(CultureInfo.InvariantCulture, "<a href='javascript:' onclick='IMNImageOnClick();return false;' class='ms-imnlink'><img name='imnmark' title='' border='0' height='12' width='12' src='/_layouts/images/blank.gif' alt='{0}' sip='{1}' id='imn_{2},type=smtp'/></a>", new object[] { SPHttpUtility.HtmlEncode(valueToEncode), SPHttpUtility.HtmlEncode(email), num.ToString(CultureInfo.InvariantCulture) });
//                }
//                return "<img border='0' height='12' width='12' src='/_layouts/images/blank.gif' alt=''>";
//            }
//            return string.Format(CultureInfo.InvariantCulture, "<a href='javascript:' onclick='IMNImageOnClick();return false;' class='ms-imnlink'><img name='imnmark' title='' border='0' height='12' width='12' src='/_layouts/images/blank.gif' alt='{0}' sip='{1}' id='imn_{2},type=sip'/></a>", new object[] { SPHttpUtility.HtmlEncode(valueToEncode), SPHttpUtility.HtmlEncode(sip), num.ToString(CultureInfo.InvariantCulture) });
//        }
        #endregion

        protected override DataControlField CreateField()
        {
            return new UserColumn();
        }
    }
}
